import {reactive} from "vue";
import {getLoginUserUsingGet} from "@/api/UserRequest";
import ACCESS_ENUM from "@/common/AccessEnum";
import {defineStore} from "pinia";

export const useLoginUserStore = defineStore('loginUser' , ()=>{
    let loginUser = reactive({
        id: 0,
        userRole: 'notLogin',
        userName: "未登录",
        userProfile: '个人简介信息',
        userAvatar: '',
    });

    const storeUser = localStorage.getItem("loginUser");
    if(storeUser){
        Object.assign(loginUser, JSON.parse(storeUser));
    }

    function isLogin(){
        return loginUser.id !== 0;
    }

    async function fetchLoginUser() {
        const res = await getLoginUserUsingGet();
        if (res.data.code === 0 && res.data.data) {
            Object.assign(loginUser, res.data.data);
            console.log(loginUser.userAvatar);
            localStorage.setItem("loginUser" , JSON.stringify(res.data.data));
        } else {
            loginUser = { userRole: ACCESS_ENUM.NOT_LOGIN };
            console.log(loginUser);
        }
    }

    function clearLoginUser() {
        loginUser.id = 0;
        loginUser.userRole = ACCESS_ENUM.NOT_LOGIN;
        loginUser.userName = "未登录";
        localStorage.clear();
        sessionStorage.clear();
        console.log('LocalStorage cleared:', localStorage.length === 0);
        console.log('SessionStorage cleared:', sessionStorage.length === 0);
    }
    return { loginUser, fetchLoginUser ,clearLoginUser , isLogin};
})